<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');
error_reporting(E_ERROR);

require_once dirname(__FILE__) ."/lib/WxPay.Api.php";
require_once dirname(__FILE__) .'/lib/WxPay.Notify.php';
require_once dirname(__FILE__) .'/log.php';

//初始化日志
$logHandler= new CLogFileHandler(dirname(__FILE__) ."/logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
			global $INI;
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			//DO
			
			$out_trade_no = $result['out_trade_no']; 
			$trade_no = strval($result['transaction_id']);
			$total_fee = $result['total_fee'] / 100;
			
			
			@list($_, $order_id, $city_id, $_) = explode('-', $out_trade_no, 4);
			
			$order = Table::FetchForce('order', $order_id);
			$team = Table::FetchForce('team', $order['team_id']);
			$user = Table::Fetch('user', $order['user_id'], 'id');
			
			$access_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.WxPayConfig::APPID.'&secret='.WxPayConfig::APPSECRET;
			$accss_token_arr = json_decode(http_get($access_url));
			$re_access_token = $accss_token_arr->access_token;
			
			$openId = $user['open_id'];
				
			
			if($order['is_pin']==1)
			{
				$pin_order = DB::LimitQuery('pin_order_list', array(
					'condition' => array('order_id'=>$order_id),
					'one' => true,
				));
				//$order  pin_id
				if(isset($INI['system']['secsite']) && !empty($INI['system']['secsite']))
					$txt ='{
						"touser":"'.$openId.'",
						"msgtype":"news",
						"news":{
							"articles": [
							 {
								 "title":"付款成功",
								 "description":"恭喜参团成功!马上叫小伙伴来参团，组团成功才能享受优惠哦",
								 "url":"'.$INI['system']['wwwprefix'].$INI['system']['secsite'].'account/group.php?id='.$order_id.'&act=pin&show=1",
								 "picurl":""
							 }
							 ]
						}
					}';
				else 
					$txt ='{
						"touser":"'.$openId.'",
						"msgtype":"news",
						"news":{
							"articles": [
							 {
								 "title":"付款成功",
								 "description":"恭喜参团成功!马上叫小伙伴来参团，组团成功才能享受优惠哦",
								 "url":"'.$INI['system']['wwwprefix'].'account/group.php?id='.$order_id.'&act=pin&show=1",
								 "picurl":""
							 }
							 ]
						}
					}';

			} else {
				$txt ='{
				"touser":"'.$openId.'",
				"msgtype":"text",
				"text":
					{
						 "content":"您已成功购买:'.$team['title'].'，订单号:'.$order_id.',于'.date('Y-m-d H:i:s').'."
					}
				}';
			}
			Log::DEBUG("custom mes:" . $txt.'accesstoken:'.$re_access_token);
			$url ='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$re_access_token;
			if($order['state'] =='unpay')
				$res = https_post($url,$txt);
			
			
			$currency = $result['fee_type'];
			$service = 'wxpay';
			$bank = '微信支付';
			ZOrder::OnlineIt($order_id, $out_trade_no, $total_fee, $currency, $service, $bank,$trade_no,WxPayConfig::MCHID);
		
			return true;
		}
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		return true;
	}
}

Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);

function http_get($url)
{
	
	$curl = curl_init();
	curl_setopt($curl,CURLOPT_URL,$url);
	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
	curl_setopt($curl,CURLOPT_POST,1);
	curl_setopt($curl,CURLOPT_POSTFIELDS,array());
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($curl);
	curl_close($ch);
	return $result;
}


function https_post($url,$data)
{
	$curl = curl_init();
	curl_setopt($curl,CURLOPT_URL,$url);
	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
	curl_setopt($curl,CURLOPT_POST,1);
	curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($curl);
	if(curl_errno($curl)){
	  return 'Errno'.curl_error($curl);
	}
	curl_close($curl);
	return $result;
}
